﻿using Barcode_Project.Entity;
using Barcode_Project.Local;
using Barcode_Project.Network;
using DevExpress.XtraEditors;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.WebRequestMethods;

namespace Barcode_Project.PurchasePrint
{
    public partial class BuyPrint : DevExpress.XtraEditors.XtraForm
    {
        //PurchasePrintQuery buyQuery { get; set; }
        Dictionary<string, string> datas;
        HttpAgreement http;
        ILog _log;
        public BuyPrint(Dictionary<string, string> pars)
        {
            _log = LogManager.GetLogger(GetType().Name);
            http = new HttpAgreement();
            InitializeComponent();

            datas = pars;

            new ComputerTask().LoadPrinter(select_printer);
            new ComputerTask().LoadTemplate(select_template);

            LoadPrintedBarCodes();
        }
        private void BuyPrint_Load(object sender, EventArgs e)
        {
            try
            {
                //MessageBox.Show(JsonConvert.SerializeObject(datas));

                CommonMethods.SetFormValue(this.group_data.Controls, datas, "input_");
                //LoadCuttedBarCodes();

                SetCheckValue();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void LoadPrintedBarCodes()
        {
            var uploadDic = new Dictionary<string, string>();
            uploadDic["cCode"] = datas["cCode"];
            uploadDic["irowno"] = datas["irowno"];

            string url = CommonMethods.APIUrl() + "GetPrintedBarcodes_ByRdrecord01_cCode_iRowNo";

            var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                var list = JsonConvert.DeserializeObject<List<PrintedBarcode>>(obj["data"].ToString());
                gridControl_printedBarcodes.DataSource = list;
                gridControl_printedBarcodes.RefreshDataSource();
            }

            //var list = new RemoteRequest()
            //    .GetPrintedBarcodes_ByRdrecord01_cCode_iRowNo(datas["cCode"], datas["irowno"]);

            //gridControl_printedBarcodes.DataSource = list;
            //gridControl_printedBarcodes.RefreshDataSource();
        }

        private void button_print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!this.button_print.Enabled)
            {
                return;
            }

            this.button_print.Enabled = false;

            CommonMethods.SetParameterValue(ref datas, this.group_data.Controls, "input_");

            if (!CheckBeforePrint())
            {
                this.button_print.Enabled = true;
                return;
            }

            var uploadDic = CollectData();

            string url = CommonMethods.APIUrl() + "SaveBarCode";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(uploadDic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.button_print.Enabled = true;
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                var msg = "";
                if (obj["message"] != null && !string.IsNullOrWhiteSpace(obj["message"].ToString()))
                {
                    msg = obj["message"].ToString();
                }
                var table = CommonMethods.CreatePrintTableByDictionary(datas, obj["data"].ToString(), msg);

                if (!table.Columns.Contains("proCode"))
                {
                    table.Columns.Add("proCode");
                }
                if (!table.Columns.Contains("proName"))
                {
                    table.Columns.Add("proName");
                }
                if (!table.Columns.Contains("spec"))
                {
                    table.Columns.Add("spec");
                }

                foreach (DataRow row in table.Rows)
                {
                    row["proCode"] = row["cInvCode"];
                    row["proName"] = row["cInvName"];
                    row["spec"] = row["cInvStd"];
                }



                var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
                var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;//模板路径

                new ComputerTask().StartPrintingTask(table, printerName, templatePath);
                //重新加载已打印条码列表

            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.button_print.Enabled = true;
                return;
            }

            this.button_print.Enabled = true;
        }

        // 打印之前，检查必填项
        bool CheckBeforePrint()
        {
            var result = false;

            if (input_cu_shelfLife.EditValue == null || string.IsNullOrEmpty(input_cu_shelfLife.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写质保期");
                return false;
            }
            if (input_cu_qualityLevel.EditValue == null || string.IsNullOrEmpty(input_cu_qualityLevel.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写质量等级");
                return false;
            }
            if (input_proWeight.EditValue == null || string.IsNullOrEmpty(input_proWeight.EditValue.ToString()))
            {
                XtraMessageBox.Show("请输入重量");
                return false;
            }
            //if (input_proMeter.EditValue == null || string.IsNullOrEmpty(input_proMeter.EditValue.ToString()))
            //{
            //    XtraMessageBox.Show("请输入米数");
            //    return false;
            //}

            if (input_cu_shelfLifeUnit.EditValue == null || string.IsNullOrEmpty(input_cu_shelfLifeUnit.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写保质期单位");
                return false;
            }
            //if (input_memo.EditValue == null || string.IsNullOrEmpty(input_memo.EditValue.ToString()))
            //{
            //    XtraMessageBox.Show("请填写备注");
            //    return false;
            //}

            if (select_printer.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印机");
                return result;
            }
            if (select_template.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印模板");
                return result;
            }

            result = true;
            return result;
        }

        Dictionary<string, string> CollectData()
        {
            datas["printNumber"] = input_printNumber.EditValue.ToString();
            datas["weight"] = input_proWeight.EditValue.ToString();
            datas["barType"] = "CG";
            if (input_proMeter.EditValue ==null ||string.IsNullOrEmpty(input_proMeter.EditValue.ToString()))
                datas["proMeter"] = "0";
            else
                datas["proMeter"] = input_proMeter.EditValue.ToString();
            datas["proWeight"] = input_proWeight.EditValue.ToString();

            //datas["number"] = input_iQuantity.EditValue.ToString();
            datas["boxCode"] = input_cBatch.EditValue.ToString();

            datas["cu_qualityLevel"] = input_cu_qualityLevel.EditValue.ToString();
            datas["cu_shelfLife"] = input_cu_shelfLife.EditValue.ToString();
            datas["memo"] = input_memo.Text.ToString();

            if (cb_check.EditValue.ToString() == "是")
            {
                datas["isCheck"] = "1";
            }
            else
            {
                datas["isCheck"] = "0";
            }

            return datas;
        }

        private void button_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void button_refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadPrintedBarCodes();
        }

        private void input_manual_EditValueChanged(object sender, EventArgs e)
        {
            led_weight.Value = input_proWeight.EditValue.ToString();
        }

        private void btn_update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var r = XtraMessageBox.Show("即将关闭程序进行升级，是否继续？", "提示", MessageBoxButtons.OKCancel);
            if (r == DialogResult.OK)
            {
                new RemoteRequest().UpdateCmdProgram();
            }
        }

        void SetCheckValue()
        {
            cb_check.Properties.Items.AddRange(new object[]
            {
                "是","否"
            });

            //// 如果是复合工序，默认为是
            //if (datas["gxCode"] == "FH")
            //{
            cb_check.SelectedIndex = 1;
            //}
            //else
            //{
            //    cb_check.SelectedIndex = 1;
            //}
        }
    }
}